<?php
namespace Operator\Model;

/**
 * 订购中心
 */
class OrderCenterModel extends BaseModel
{
    /**
     * 查询匹配线路
     * @return array
     */
    public function getLine()
    {
        $operator_id = session('operator_user.pid') ? session('operator_user.pid') : session('operator_user.operator_id');
        $p           = I('p', 1);
        $limit       = 10;
        $start       = ($p - 1) * $limit;
        //查询该分销上有权限的线路id
        $sql     = " SELECT line_id from __OPERATOR_SALES_CHANNEL__ where channel_type = 1 or find_in_set({$operator_id},seller_id)";
        $line_id = M()->query($sql);
        if (empty($line_id)) {
            return false;
        }
        $line_id = implode(',', array_map('array_shift', $line_id));
        //目的地优先 文字输入的
        $destination = I('arrive') ? I('arrive') : I('city');

        //通过城市名检索城市id
        if ($destination) {
            $destination = $this->findCity($destination);
            $data .= " and FIND_IN_SET('{$destination}', destination_id) ";
        }

        //出发地
        if (I('set_out')) {
            $set_out = $this->findCity(I('set_out'));
            $data .= " and origin_id = {$set_out}";
        }

        //线路价格
        if (I('min_price')) {
            $data .= " and total_cost > " . I('min_price');
        }

        if (I('max_price')) {
            $data .= " and total_cost < " . I('max_price');
        }

        //线路名称
        if (I('line_name')) {
            $line_name = I('line_name');
            $data .= " and  line_name like '%{$line_name}%' ";
        }

        //団号
        if (I('line_sn')) {
            $line_sn = I('line_sn');
            $data .= " and line_sn = '{$line_sn}' ";
        }

        //旅游天数
        if (I('day')) {
            $day = I('day');
            if ($day == 11) {
                $data .= " and  travel_days >= 11 ";
            } else {
                $data .= " and travel_days = '{$day}' ";
            }
        }

        //线路状态为上架,时间在出团与收团之间
        $time = time();
        $data = "  l.line_id in ({$line_id}) and line_status= 1 and is_show = 1  " . $data;
        $line = M('public_line as l')
            ->field('l.line_id,l.line_sn,origin_id,l.group_num,l.line_name,source_type,
                destination_id,travel_days,r.adult_price,child_price,oldman_price')
                // start_time - till_day*86400 as till,start_time - book_day*86400 as book')
            ->field('l.line_id,l.line_sn,origin_id,l.group_num,l.line_name,
                destination_id,travel_days,r.adult_price,child_price,oldman_price')
            ->join("__LINE_RESELLER_PRICE__ as r on r.line_id = l.line_id and ((r.reseller_id = '{$operator_id}' and r.rp_type = 1) or r.rp_type=0)")
            ->where($data)
            ->limit($start, $limit)
            // ->having("{$time} between book and till")
            ->order('line_sort asc,l.line_id desc')
            ->select();
        $this->arrangeData($line);

        $count = M('public_line as l')
            ->join("__LINE_RESELLER_PRICE__ as r on r.line_id = l.line_id and ((r.reseller_id = '{$operator_id}' and r.rp_type = 1) or r.rp_type=0)")
            ->where($data)
            // ->having("{$time} between book and till")
            ->getField('count(l.line_id)');

        unset($data);
        return ['total' => $count, 'root' => $line, 'limit' => $limit];
    }

    /**
     * 搜索城市名称
     * @param  [string] $city_name [城市名称]
     * @return [string]            [城市id(多个结果  用,拼接)]
     */
    private function findCity($city_name)
    {
        $res = M('areas')
            ->field('areaId')
            ->where([
                'isShow'   => 1,
                'areaFlag' => 1,
                'areaType' => 1,
                'areaName' => ['like', "{$city_name}%"],
            ])
            ->select();
        return implode(',', array_map('array_shift', $res));
    }

    /**
     * 把目的地信息id转换成name
     * @param array $arr 需要转换的数据
     */
    private function arrangeData(&$arr)
    {
        $areas = [];
        $temp  = M('areas')
            ->field('areaId,areaName')
            ->where(['isShow' => 1, 'areaFlag' => 1, 'areaFlag' => 1])
            ->select();

        foreach ($temp as $k => $v) {
            $areas[$v['areaId']] = $v['areaName'];
        }
        unset($temp);

        foreach ($arr as $k => $v) {
            $dest_arr      = explode(',', $v['destination_id']);
            $dest_temp_arr = [];
            foreach ($dest_arr as $dest) {
                if (isset($areas[$dest])) {
                    $dest_temp_arr[] = $areas[$dest];
                }
            }
            $arr[$k]['source_type']      = $v['source_type'] == 1 ? '(自营)' : '';
            $arr[$k]['origin']           = $areas[$v['origin_id']];
            $arr[$k]['destination_name'] = implode(',', $dest_temp_arr);
            unset($dest_temp_arr);
        }

    }

    /**
     * 返回地址信息
     * @return [type] [description]
     */
    public function getAreas()
    {
        $key = md5('getAreas');
        if (!S($key)) {
            $temp = M('areas')
                ->field('areaId,areaName,parentId')
                ->where([
                    'isShow'   => 1,
                    'areaFlag' => 1,
                    'areaType' => ['lt', 2],
                ])
                ->order('areaSort')
                ->select();
            S($key, $this->createTree($temp, 'areaId', 'parentId'), 86400);
        }
        return S($key);
    }

    /**
     * 生成树状数据
     * @param array $temp 需要整理的数据
     * @param int   $id    主键键名
     * @param int   $pid   父级id键名
     * @return array
     */
    private function createTree($temp, $id, $pid)
    {
        $areas = [];

        foreach ($temp as $v) {
            $areas[$v[$id]] = $v;
        }

        $tree = [];
        foreach ($areas as $k => $v) {

            //如果存在上级区域
            if ($areas[$v[$pid]]) {
                // dump($areas[$v[$id]]);
                $areas[$v[$pid]]['son'][] = &$areas[$v[$id]];
            } else {
                $tree[] = &$areas[$v[$id]];
            }

        }
        return $tree;
    }

}
